function [ y ] = signed_modularity( x, network )
%SIGNED_MODULARITY: Calculate the value of signed modularity.
%   x: The label of an individual or a struct of the new_data;
%   y: The value of the signed modularity. 

% global network;
index1 = (network==-1);
index2 = (network==1);
pos_m = sum(sum(index2));
neg_m = sum(sum(index1));
m = pos_m + neg_m;

signed_Q = 0;
if isstruct(x)        % if x is a structure variable.
    label = x.label;
    k = max(label);
    for i = 1:k
        index = find(label == i);
        S = network(index,index);
        li = sum(sum(S));
        pos_di = 0; neg_di = 0;
        for j = 1:length(index)
            neg_di = neg_di + length(x.adjacent_nodes.neg_adjacent{index(j)});
            pos_di = pos_di + length(x.adjacent_nodes.pos_adjacent{index(j)});
        end
        if (neg_m > 0) && (pos_m > 0)
            signed_Q = signed_Q + li + (neg_di^2)/neg_m - (pos_di^2)/pos_m;
        elseif (neg_m == 0) && (pos_m > 0)
            signed_Q = signed_Q + li  - (pos_di^2)/pos_m;
        elseif (neg_m > 0) && (pos_m == 0)
            signed_Q = signed_Q + li + (neg_di^2)/neg_m;
        else
            error('Something wrong with signed modularity.\n');
        end
    end
else                % or x is the label of an individual.        
    label = x;
    k = max(label);
    for i = 1:k
        index = find(label == i);   
        S = network(index,index);
        li = sum(sum(S));
        pos_di = 0; neg_di = 0;
        for j = 1:length(index)
            di = network(index(j),:);
            tempi1 = (di > 0);
            tempi2 = (di < 0);
            pos_di = pos_di + sum(tempi1);
            neg_di = neg_di + sum(tempi2);
        end
        if (neg_m > 0) && (pos_m > 0)
            signed_Q = signed_Q + li + (neg_di^2)/(neg_m) - (pos_di^2)/(pos_m);        
        elseif (neg_m == 0) && (pos_m > 0)
            signed_Q = signed_Q + li - (pos_di^2)/(pos_m);
        elseif (neg_m > 0) && (pos_m == 0)
            signed_Q = signed_Q + li + (neg_di^2)/(neg_m);
        else
            error('Something wrong with signed modularity.\n');
        end
    end
end

y = signed_Q/(m);

end
